package com.schoolgard.action.googlemap;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import net.sf.json.JSONArray;

import com.schoolegard.services.LocationService;
import com.schoolgard.base.BaseAction;
import com.schoolgard.entitybean.Location;

public class LocationAction extends BaseAction{

	private LocationService locationService;
	
	
    public void saveLocation()
    {
    	String location = request.getParameter("location");
    	String nodeId = request.getParameter("nodeId");
    	String locationName = request.getParameter("locationName");
    	Location loca = null;
    	loca = locationService.findLocaBySPNodeId(nodeId);
    	if(loca == null){
    		loca = new Location();
    		String refId = null;
    		if(nodeId.indexOf("re_") != -1){
    			loca.setType("REGIONS");
    			refId = nodeId.replace("re_", "");
    		}else if(nodeId.indexOf("or_") != -1){
    			loca.setType("ORGANIZATION");
    			refId = nodeId.replace("or_", "");
    		}else if(nodeId.indexOf("de_") != -1){
    			loca.setType("DEVICE");
    			refId = nodeId.replace("de_", "");
    		}
    		loca.setRefId(refId);
    	}
		loca.setLocationName(locationName);
    	String[] locaa = location.split(",");
    	if(locaa != null && locaa.length ==2){
    		loca.setXAxis(locaa[0].trim());
    		loca.setYAxis(locaa[1].trim());
    		try{
        		locationService.saveOrUpdate(loca);
        		writeToResponse("1");
        	}catch (Exception e) {
    			e.printStackTrace();
    			writeToResponse("0");
    		}
    	}else{
    		writeToResponse("0");
    	}
    	
    }	
    
    public void findLocation()
    {
    	List<Location> locls = locationService.findLocation();
	   	String jsonStr = JSONArray.fromObject(locls).toString();
	   	writeToResponse(jsonStr);
    }
	
    public void delete(){
    	String id = request.getParameter("locationId");
    	if(StringUtils.isNotEmpty(id)){
    		locationService.delete(Long.valueOf(id));
    		writeToResponse("1");
    	}else{
    		writeToResponse("0");
    	}
    }
	
	public void setLocationService(LocationService locationService) {
		this.locationService = locationService;
	}
}
